package com.atjava.nebula.weixin;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.atjava.nebula.core.exception.baseExp.BusinessException;
import com.atjava.nebula.core.service.GenericService;
import com.atjava.nebula.frames.user.SysUser;
import com.atjava.nebula.web.action.BaseViewAction;
import com.atjava.nebula.weixin.ssl.WeixinConst;
import com.atjava.nebula.weixin.ssl.WeixinHttpsApiCaller;

@Controller
@RequestMapping("/weixin")
public class WeixinAction extends BaseViewAction{
	
	@RequestMapping(value="/auth/login")
	public String login(@RequestParam("code") String code,
			HttpServletRequest request, 
			HttpServletResponse response)
			throws Exception{
		
		String userId = WeixinHttpsApiCaller.getUserId(code);
		
		GenericService<SysUser,String> userService = getService(SysUser.class,String.class);
		
		SysUser user = userService.getById(userId);
		String directPath;
		
		if(user == null){
			user = new SysUser();
			user.setUserId(userId);
			directPath = "/weixin/bind-userinfo";
		}else{
			//user.setLastLoginIp(request.getRemoteAddr());
			user.setLastLoginTime(new Date());
			userService.updateAllById(user);
			directPath = "/weixin/auto-login";
		}
		
		HttpSession session = request.getSession();
		session.setAttribute(WeixinConst.SECURITY_SESSKEY_WEIXIN_LOGIN, true);
		request.setAttribute(MODEL_KEY_SYSUSER, user);
		return directPath;
	}
	
	
	@RequestMapping(value="/auth/binduser" ,method = RequestMethod.POST)
	public String bindUser(@RequestParam("userId") String userId,
			@RequestParam("password") String password,
			HttpServletRequest request, 
			HttpServletResponse response)
			throws Exception{
		
		HttpSession session = request.getSession();
		Object weixinLogin = session.getAttribute(WeixinConst.SECURITY_SESSKEY_WEIXIN_LOGIN);
		if(weixinLogin == null){
			throw new BusinessException("请从微信客户端访问！");
		}
		
		GenericService<SysUser,String> userService = getService(SysUser.class,String.class);
		
		SysUser user = new SysUser();
		user.setCreateTime(new Date());
		user.setUpdateTime(new Date());
		user.setUserId(userId);
		Md5PasswordEncoder encoder = new Md5PasswordEncoder();
		user.setPassword(encoder.encodePassword(password, userId));
		try {
			userService.create(user);
		} catch (Exception e) {
			throw new BusinessException("用户["+userId+"]已绑定，请不要重复绑定！");
		}
		request.setAttribute(MODEL_KEY_SYSUSER, user);
		
		return "/weixin/auto-login";
	}
	
}
